/*
Copyright (C) 2015 Marien Raat

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <player.h>
#include <math.h>

#define PI 3.1415926535897932384

Player::Player(sf::Vector2f startPosition, float rotationInRad,
               float radius, sf::Vector2u screenSize)
{
    this->position = startPosition;
    this->rotationInRad = rotationInRad;
    this->radius = radius;
    this->screenSize = screenSize;
}

bool Player::update()
{
    bool dead = false;
    position += (sf::Vector2f(cos(rotationInRad)
                              , sin(rotationInRad)) * speed);

    // Handle collision with walls
    if (position.x < radius) {
        position.x = radius;
    }
    if (position.x > (screenSize.x - radius)) {
        position.x = screenSize.x - radius;
        dead = true;
    }
    if (position.y < radius) {
        position.y = radius;
        dead = true;
    }
    if (position.y > (screenSize.y - radius)) {
        position.y = screenSize.y - radius;
        dead = true;
    }

    // Trim rotation
    if (rotationInRad > 2.0 * PI) rotationInRad -= 2.0 * PI;
    if (rotationInRad < -2.0 * PI) rotationInRad += 2.0 * PI;

    return dead;
}

void Player::turnLeft()
{
    rotationInRad -= (turnSpeed / sqrt(radius));
}

void Player::turnRight()
{
    rotationInRad += (turnSpeed / sqrt(radius));
}

sf::Vector2f Player::getPosition()
{
    return position;
}

float Player::getRotation()
{
    return rotationInRad / PI * 180.0;
}

float Player::getRadius()
{
    return radius;
}

void Player::addCell(float cellRadius)
{
    float cellArea = PI * pow(cellRadius, 2.0);
    float myArea = PI * pow(radius, 2.0);
    float newArea = myArea + (cellArea / 2.0);
    radius = sqrt(newArea / PI);
}
